import java.io.*;
import java.net.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;



public class ArdHandler extends Thread
{
	
	private Socket clientSocket;
	private InputStreamReader isr;
	private OutputStream os;
	private Connection connect;
	
	private SharedObject sharedObject;
	private int clientID;
	static String tempa="";
	static boolean temp=false;
	
	public ArdHandler(Socket clientSocket,SharedObject sharedObject,int clientID)
	{
		this.clientSocket = clientSocket;
		this.sharedObject = sharedObject;
		this.clientID = clientID;
		
		sharedObject.addArdClient(clientSocket, clientID);
	}
	public void run(){
		readDatabase();
		try {
			isr=new InputStreamReader(clientSocket.getInputStream());
			os=clientSocket.getOutputStream();
			
			BufferedReader br=new BufferedReader(isr);
			PrintWriter pw=new PrintWriter(os,true);
			
			
			//request command that the house sends, not used at the moment, will ask the house to send the status of all its devices
			///pw.println("request");
//			String deviceStates=br.readLine();
			
			//System.out.println(deviceStates);
			//updateDeviceStates(deviceStates);
				
			
			//reading from house
			while(!clientSocket.isClosed())
			{
				
				if(!ClientHandler.temp && clientSocket.getInputStream().available() > 0){
					
				String unit=br.readLine();
					
				System.out.println(unit);
							
				String parse[]=unit.split(":");
			
				System.out.println("server:"+ parse.length);
				
				if(parse[0].equalsIgnoreCase("temp")){
					//System.out.println("Here we stop the loop, sharedobject is now reading");
					
					//System.out.println("sending temp to specific client");
					
				//	sharedObject.sendInformationSpec(Integer.parseInt(parse[2]), parse[1]);

				}
				else
				{
					Statement st;
					
					try 
					{
						st = connect.createStatement();
						if(parse.length>0){
						st.execute("UPDATE devices SET state='" + parse[1] + "' WHERE deviceName='" + parse[0] + "';");
						}
					
						//can uncomment row if we want to send any changes to the clients, (if something happens physically in the house)
					//sharedObject.sendInformation(unit);
						
					} catch (SQLException e) {
						e.printStackTrace();
					}
				}
				
				//pw.println(unit);
			}
				}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	public void readDatabase()
	{
		try 
		{
			//establish a connection the the database, username root and password 123
			Class.forName("com.mysql.jdbc.Driver");
			connect = DriverManager.getConnection("jdbc:mysql://localhost/projectdb", "root", "");
			Statement stmt = connect.createStatement();
			stmt.execute("USE projectdb");
		} 
		catch(SQLException e) 
		{
			e.printStackTrace();
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}
	//used for the request command, add all the devices that the house sends to this thread
	public void updateDeviceStates(String deviceStates) 
	{
		String[] devices = deviceStates.split(",");
		
		Statement stmt=null;
		try {
			stmt = connect.createStatement();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		for(int i =0; i < devices.length; i++)
		{
			String[] update = devices[i].split(":");
			
			ResultSet rs;
			try {
				rs = stmt.executeQuery("SELECT deviceName,state FROM devices WHERE deviceName='" + update[0] + "';");
				if(rs.next())
				{
					stmt.execute("UPDATE devices SET state='" + update[1] + "' WHERE deviceName='" + update[0] + "';");
				}
				else
				{
					stmt.executeUpdate("INSERT INTO devices VALUES(default, "+ update[0] +", "+update[1]+");");
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}	
		}
	}	
}
 